/**
 * 插件配置加载以及动态执行插件
 * create by @author lms 2018.05.09
 */
package ms.core.serv.tool;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import ms.core.serv.dto.Api;
import ms.core.tool.Log4j2Tool;
import ms.core.tool.StreamTool;

public class ApiLoader {
	private static String fileName = "/config/api.xml";
	private static Map<String, Api> apis;

	public static void init() {
		apis = new HashMap<String, Api>();
		try{
			InputStream in = StreamTool.loadFileToStream(ApiLoader.class, fileName);
			SAXReader reader = new SAXReader();
			Document doc = reader.read(in);
			Element root = doc.getRootElement();
			List<Element> items = root.elements();
			for(Element item : items){
				Api api = new Api();
				api.setApiName(item.attributeValue("apiName"));
				api.setClassName(item.attributeValue("className"));
				api.setFunctionName(item.attributeValue("functionName"));
				api.setLogEvent("true".equalsIgnoreCase(item.attributeValue("logEvent")));
				api.setAuth(!"false".equalsIgnoreCase(item.attributeValue("auth")));
				api.setDescription(item.attributeValue("desc"));
				apis.put(api.getApiName(),api);
			}
			in.close();
		} catch (Exception e) {
			Log4j2Tool.error(ApiLoader.class, e);
		}
	}

	public static Api getApi(String apiName) {
		return apis.get(apiName);
	}

	public static void main(String[] args) {
		ApiLoader.init();
		System.out.println(getApi("getTime"));
	}
}
